<script setup lang="ts">
import axios from "axios";
 
const send = () => {
  axios({
    method: "get",
    url: "url地址", //user.json与当前文件在同一个路径下，如果user.json不存在则返回‘请求失败’
    responseType: "json", //这句不能少 否则火狐浏览器下会报错
    //上述之后会返回一个Promise对象，然后调用该对象的then方法（也就是执行成功的回调方法）
  })
    .then(function (resp) {
      //resp表示执行成功的结果
      console.log("axios-----", resp);
    })
    .catch((err) => {
      //catch表示执行失败的调用函数 err表示失败的结果
      console.log("请求失败", err);
    });
};
 
const initWebsocket = () => {
  //初始化websocket
  let planWebsocket: any = null;
  let planIP: any = "127.0.0.1"; // IP地址
  let planPort: any = "8765"; // 端口号
  if ("WebSocket" in window) {
    planWebsocket = new WebSocket("ws://" + planIP + ":" + planPort); // 通信地址
    planWebsocket.onopen = function (event: any) {
      console.log("建立连接", event);
      let sendData = "你好啊";
      planWebsocket.send(sendData); // 发送获取数据的接口
    };
 
    planWebsocket.onmessage = function (event: any) {
      console.log("收到消息:" + event.data);
    };
 
    planWebsocket.onclose = function (event: any) {
      console.log("连接关闭", event);
    };
 
    planWebsocket.onerror = function () {
      alert("websocket通信发生错误！");
    };
  } else {
    alert("该浏览器不支持websocket!");
  }
};
 
// 发送websokcet消息
const sendWebSocket = () => {
  console.log("发送websocket消息");
  initWebsocket();
};
</script>
 
<template>
  <div class="container">
    <h1>Welcome to Tauri!</h1>
    <div>
      <button @click="send">发送axios请求</button>
      &nbsp; &nbsp; &nbsp;
      <button @click="sendWebSocket">发送Websocket</button>
    </div>
  </div>
</template>
 
<style scoped>
.logo.vite:hover {
  filter: drop-shadow(0 0 2em #747bff);
}
 
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #249b73);
}
</style>